from plugins.template import ParserTemplate
import re

def get_parsers():
	return {"Ackeejag" : Parser}

class Parser(ParserTemplate):
	"""
	Grammar:
	Page = "p" Number NL .
	Panel = "panel " Number NL.
	Text = Translation NL.

	>>> from io import StringIO
	>>> text = '''p5
	... panel 1
	... ..hm!
	... ha!!
	... panel 3
	... eh!
	... p6
	... First off
	... '''
	>>> parser = Parser(StringIO(text))
	>>> parser.next_token()
	Token(page='5', panel='1', text='..hm!', line=2)
	>>> parser.next_token()
	Token(page='5', panel='1', text='ha!!', line=3)
	>>> parser.next_token()
	Token(page='5', panel='3', text='eh!', line=5)
	>>> parser.next_token()
	Token(page='6', panel='1', text='First off', line=7)
	>>> parser.next_token()
	"""

	_PageRe = re.compile('''p(\d+)	# simple number as group
	$ # end''', re.VERBOSE | re.IGNORECASE)
	
	_PanelRe = re.compile('''panel\  # panel <space>
	(\d+) # panel number
	$  #''', re.VERBOSE | re.IGNORECASE)
	
	def __init__(self, file):
		super().__init__(file)
	
	def _parse_next(self, last_token):
		try:
			page = self._parse_re(self._PageRe)
			if page:
				panel = self._parse_re(self._PanelRe) or "1"
			else:
				page = last_token.page
				panel = self._parse_re(self._PanelRe) or last_token.panel
			line = self._cur_line
			text = self._get_line()
			self._next_line()
			return [self.Token(page, panel, text, line)]
		except self.ParserEndError:
			return [None]

if __name__ == '__main__':
	import doctest
	doctest.testmod()